package tools

import (
	"errors"
	"fmt"
	"io"
	"os/exec"
)

// 执行命令
func Execute(command string) (string, error) {
	cmd := exec.Command("/bin/bash", "-c", command)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println("StdoutPipe: " + err.Error())
		return "", err
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Println("StderrPipe: " + err.Error())
		return "", err
	}
	if err := cmd.Start(); err != nil {
		fmt.Println("Start: ", err.Error())
		return "", err
	}
	bytesErr, err := io.ReadAll(stderr)
	if nil != err {
		return "", err
	}
	bytesOut, err := io.ReadAll(stdout)
	if nil != err {
		return "", err
	}
	if err := cmd.Wait(); err != nil {
		fmt.Println("Wait: ", err.Error())
		return "", err
	}
	if len(bytesErr) != 0 {
		return "", errors.New(string(bytesErr))
	}

	return string(bytesOut), nil
}
